package gqz.testdemo.BtBleDemo;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import gqz.testdemo.R;

/**
 * Created by Administrator on 2018/9/18.
 */

public class RvAdapter extends RecyclerView.Adapter<RvAdapter.RvHolder> {
    private Context mContext;
    private List<BluetoothDevice> mDevices;
    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public RvAdapter(Context mContext) {
        this.mContext = mContext;
        mDevices = new ArrayList<>();
    }

    @Override
    public RvHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new RvHolder(LayoutInflater.from(mContext).inflate(R.layout.item_ble, parent, false));
    }

    @Override
    public void onBindViewHolder(RvHolder holder, final int position) {
        holder.nameTv.setText(mDevices.get(position).getName() + ":" + mDevices.get(position).getAddress());
        //点击事件 点击配对
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickListener.onClick(mDevices.get(position));
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mDevices.size();
    }

    public void addDevice(BluetoothDevice dev) {
        Log.i("RvAdapter-->", "onReceive: name:" + dev.getName() + " address:" + dev.getAddress());
        boolean flag = false;
        String addr = dev.getAddress();
        BluetoothDevice rawDev = null;
        for (BluetoothDevice bd : mDevices) {
            if (bd.getAddress().equals(addr)) {
                flag = true;
                rawDev = bd;
                break;
            }
        }
        if (!flag) {
            mDevices.add(dev);
            notifyItemInserted(mDevices.size() - 1);
        }
        if (rawDev != null) {
            if (dev.getName() != null && !dev.getName().equals(rawDev.getName())) {
                mDevices.set(mDevices.indexOf(rawDev), dev);
                notifyItemChanged(mDevices.indexOf(rawDev));
            }
        }
    }

    public void clearDevices() {
        mDevices.clear();
        notifyDataSetChanged();
    }

    public interface OnItemClickListener {
        void onClick(BluetoothDevice device);
    }

    class RvHolder extends RecyclerView.ViewHolder {
        private TextView nameTv;

        public RvHolder(View itemView) {
            super(itemView);
            nameTv = itemView.findViewById(R.id.name);
        }
    }
}
